import React from 'react'
import classnames from 'classnames'
import {NavLink} from 'react-router-dom'
import { connect } from 'react-redux'
import './pad';

const mapStateToProps = (state) => {
  return {
    gameData: state.app.gameData
  }
}
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    // openCreateGame: (gameData) => dispatch(global.allActions.appActions.openCreateGame(gameData)),
  }
}
class BattlePad extends React.Component<any, any> {
  private fastTurnPageTime: number = 200
  private normalTurnPageTime: number = 0
  private hammerThrehold: number = 12
  private turnPageThreshold: number = 20
  private addPanTime: number = 360
  private HammerManager: any
  private Pan: any
  normalTurnPage: boolean = false
  fastTurnPage: boolean = false

  public constructor(props) {
    super(props)
    this.onpanStart = this.onpanStart.bind(this)
    this.onpanEnd = this.onpanEnd.bind(this)
    this.onpanLeft = this.onpanLeft.bind(this)
    this.onpanRight = this.onpanRight.bind(this)
    this.goPage = this.goPage.bind(this)
    this.state = {
      width: 0,
      height: 0,
      deltaX: 0,
      startX: 0,
      activePageIndex: 0
    }
  }

  public componentDidMount() {
    const domElement = document.getElementById('gamepadContainer')
    const HammerManager = new Hammer.Manager(domElement)
    const Pan = new Hammer.Pan({
      event: 'pan',
      pointers: 0,
      threshold: this.hammerThrehold,
      direction: Hammer.DIRECTION_HORIZONTAL
    })
    this.Pan = Pan
    this.HammerManager = HammerManager
    HammerManager.on('panstart', this.onpanStart)
    HammerManager.on('panend', this.onpanEnd)
    HammerManager.on('panleft', this.onpanLeft)
    HammerManager.on('panright', this.onpanRight)
    HammerManager.add(Pan)
    this.setState({width: domElement.offsetWidth, height: domElement.offsetHeight})
  }

  public onpanStart(event) {
    this.setState({startX: 0})
    this.noAnimationPage()
  }

  public onpanEnd(event) {
    const {
      deltaY,
      deltaX,
      additionalEvent
    } = event
    this.setState({startX: 0})

    // 不翻页
    let tooNear = Math.abs(deltaX) <= 25
    if (tooNear || _.flatten(this.props.gameData).length <= 10) {
      this.notTurnPage()
      return
    }
    // 往左滑翻页
    if (additionalEvent === 'panleft' || deltaX < 0) {
      this.leftTurnPage()
      return
    }

    // 往右滑翻页
    if (additionalEvent === 'panright' || deltaX > 0) {
      this.rightTurnPage()
      return
    }
  }

  public onpanLeft(event) {
    let {
      deltaX
    } = event
    this.setState({deltaX: this.state.startX + deltaX})
  }

  public onpanRight(event) {
    let {
      deltaX
    } = event
    this.setState({deltaX: this.state.startX + deltaX})
  }

  normalPage() {
    this.normalTurnPage = true
    this.fastTurnPage = false
  }

  fastPage() {
    this.normalTurnPage = false
    this.fastTurnPage = true
  }

  noAnimationPage() {
    this.normalTurnPage = false
    this.fastTurnPage = false
  }

  public notTurnPage() {
    this.fastPage()
    this.setState({deltaX: 0})
    this.HammerManager.remove(this.Pan)
    setTimeout(() => {
      this.HammerManager.add(this.Pan)
    }, this.addPanTime)
  }

  public get pageListPaged() {
    return _.chunk(this.props.gameData, 10)
  }

  public leftTurnPage() {
    // this.normalPage()
    setTimeout(() => {
      this.nextPage()
    }, this.normalTurnPageTime)
  }

  public rightTurnPage() {
    // this.normalPage()
    setTimeout(() => {
      this.prePage()
    }, this.normalTurnPageTime)
  }

  private nextPage() {
    this.noAnimationPage()
    const activePageIndex = this.state.activePageIndex >= this.pageListPaged.length - 1 ? 0 : this.state.activePageIndex + 1
    this.setState({activePageIndex, deltaX: 0})
  }

  private prePage() {
    this.noAnimationPage()
    const activePageIndex = this.state.activePageIndex === 0 ? this.pageListPaged.length - 1 : this.state.activePageIndex - 1
    this.setState({activePageIndex, deltaX: 0})
  }

  public goPage(activePageIndex) {
    this.setState({activePageIndex})
  }

  public componentWillUnmount() {
    if (this.state.HammerManager) {
      this.state.HammerManager.destroy()
    }
  }

  public render() {
    const {activePageStyle, prePageStyle, nextPageStyle} = this.getPageStyle()
    const {gameClicked} = this.props
    const animationCname = classnames({
      'animated-page': this.normalTurnPage,
      'animated-page-fast': this.fastTurnPage,
      'text-center': true
    })
    return (
      <div className="full relative">
        <ul className="game-page-battle" id="gamepadContainer">
          {
            this.pageListPaged.map((pageData, index) => {
              var pageStyle 
              switch (index) {
                case this.state.activePageIndex - 1:
                  pageStyle = prePageStyle
                  break
                case this.state.activePageIndex:
                  pageStyle = activePageStyle
                  break
                case this.state.activePageIndex + 1:
                  pageStyle = nextPageStyle
                  break
                default:
                  pageStyle = {display: 'none'}
                  break
              }
              return <li style={pageStyle} key={index} className={animationCname}>
                <img src="img/battle/battle-di.png?v=20181201" className="full pos-abs battle-di" alt=""/>
                <div className="pure-g games-warpper">
                {
                  pageData.map((gameData, indexGame) => {
                    const imgCname = classnames({
                      'game-icon-battle': true,
                      'second': indexGame > 1
                    })
                    const divCn = classnames({
                      'pure-u-1-2': true,
                      'pos-relative': true,
                      'first': indexGame <= 1
                    })
                    const toLink = `/BattleDetail/${gameData.gameId}/${gameData.gameName}`
                    return <div className={divCn} key={index * 10 + indexGame}>
                      {/* <NavLink to={toLink}><img src={gameData.icon} alt="" className={imgCname} onClick={this.openBattlePage.bind(this, gameData)}/></NavLink> */}
                      <img src="img/userCenter/yellows-btn.png?v=20181201" alt="" className={imgCname}/>
                      <div className="underbg" onClick={() => gameClicked(gameData)}>
                        <span className="game-name-battle">{gameData.gameName}</span>
                      </div>
                    </div>  
                  })
                }
                </div>
              </li>
            })
          }
        </ul>
        <div className="indicator-battle">
          {
            this.pageListPaged.map((game, index) => {
              return <img src={index === this.state.activePageIndex ? 'img/app/circle.png?v=20181201' : 'img/app/circle-dark.png?v=20181201'} key={index} onClick={this.goPage.bind(this, index)} alt=""/>
            })
          }
        </div>
      </div>
    )
  }

  public getPageStyle() {
    const activePageStyle = {
      transform: `translateX(${this.state.deltaX}px)`,
      WebkitTransform: `translateX(${this.state.deltaX}px)`,
      width: `${this.state.width}px`,
      height: `${this.state.height}px`
    }
    const prePageStyle = {
      transform: `translateX(-${this.state.width - this.state.deltaX}px)`,
      WebkitTransform: `translateX(-${this.state.width - this.state.deltaX}px)`,
      width: `${this.state.width}px`,
      height: `${this.state.height}px`
    }
    const nextPageStyle = {
      transform: `translateX(${this.state.width + this.state.deltaX}px)`,
      WebkitTransform: `${this.state.width + this.state.deltaX}px)`,
      width: `${this.state.width}px`,
      height: `${this.state.height}px`
    }
    return {activePageStyle, prePageStyle, nextPageStyle}
  }

}

export default connect(mapStateToProps, mapDispatchToProps)(BattlePad)